package com.leyou.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.*;
import com.leyou.item.entity.Sku;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.mapper.SpuMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.leyou.common.constants.MQConstants.Exchange.ITEM_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKey.ITEM_DOWN_KEY;
import static com.leyou.common.constants.MQConstants.RoutingKey.ITEM_UP_KEY;

@Service
public class GoodsService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    public PageResult<SpuDTO> spuPageQuery(Integer page, Integer rows, Boolean saleable, String key) {

        //开启分页
        PageHelper.startPage(page, rows);

        //动态sql生成器
        Example example = new Example(Spu.class);

        //动态条件的拼接工具
        Example.Criteria criteria = example.createCriteria();

        //模糊查询name
        if (!StringUtils.isBlank(key)) {
            criteria.andLike("name", "%" + key + "%");
        }

        //查询上下架状态
        if (null != saleable) {
            criteria.andEqualTo("saleable", saleable);
        }

        List<Spu> spus = this.spuMapper.selectByExample(example);

        if (CollectionUtils.isEmpty(spus)) {
            throw new LyException(ExceptionEnum.DATA_NOT_FOUND);
        }

        //根据查询条件统计总行数，计算总页码数
        PageInfo<Spu> pageInfo = new PageInfo<>(spus);

        List<SpuDTO> spuDTOS = BeanHelper.copyWithCollection(spus, SpuDTO.class);

        //跨业务查询，查询分类信息以及品牌信息，跨业务发生时严禁直接调用mapper，通过service调用
        spuDTOS.forEach(spuDTO -> {

            BrandDTO brandDTO = this.brandService.queryBrandById(spuDTO.getBrandId());
            spuDTO.setBrandName(brandDTO.getName());

            //根据分类的id集合查询分类的集合
            List<CategoryDTO> categoryDTOS = this.categoryService.queryCategoryByIds(spuDTO.getCategoryIds());

            //TODO 关于分类和品牌的查询其实走缓存更快

            //从分类集合中取出每个分类对象的名称，然后，把取出的名称拼接为字符串
            String names = categoryDTOS.stream()//Stream<CategoryDTO>
                    .map(CategoryDTO::getName)//Stream<String>
                    .collect(Collectors.joining("/"));//String str/str/str

            //StringUtils.join 把集合转为字符串，挨个取出每个元素，并且之间以/拼接
            spuDTO.setCategoryName(names);
        });

//        spuDTOS = spuDTOS.stream().map(spuDTO -> {
//            spuDTO.setBrandName(String.valueOf(spuDTO.getBrandId()));
//            //StringUtils.join 把集合转为字符串，挨个取出每个元素，并且之间以/拼接
//            spuDTO.setCategoryName(StringUtils.join(spuDTO.getCategoryIds(),"/"));
//
//            return spuDTO;
//        }).collect(Collectors.toList());


        return new PageResult<>(pageInfo.getTotal(), pageInfo.getPages(), spuDTOS);
    }

    @Transactional
    public void addGoods(SpuDTO spuDTO) {
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);

        //保存spu，回显spuId
        int count = this.spuMapper.insertSelective(spu);

        if (1 != count) {
            throw new LyException(ExceptionEnum.DATA_SAVE_ERROR);
        }

        SpuDetail spuDetail = BeanHelper.copyProperties(spuDTO.getSpuDetail(), SpuDetail.class);

        spuDetail.setSpuId(spu.getId());

        //保存spuDetail
        count = this.spuDetailMapper.insertSelective(spuDetail);

        if (1 != count) {
            throw new LyException(ExceptionEnum.DATA_SAVE_ERROR);
        }

        saveSkus(spuDTO, spu.getId());

        //TODO web请求，page，createHtml(spuId)
    }

    private void saveSkus(SpuDTO spuDTO, Long spuId) {
        int count;
        List<SkuDTO> skuDTOs = spuDTO.getSkus();

        List<Sku> skus = skuDTOs.stream()
                .map(skuDTO -> {
                    //给skuDTO赋值spuId
                    skuDTO.setSpuId(spuId);
                    //把skuDTO转换为sku
                    return BeanHelper.copyProperties(skuDTO, Sku.class);
                }).collect(Collectors.toList());

        count = this.skuMapper.insertList(skus);

        if (count != skus.size()) {
            throw new LyException(ExceptionEnum.DATA_SAVE_ERROR);
        }
    }

    @Transactional
    public void modifySaleable(Long spuId, Boolean saleable) {
        Spu record = new Spu();
        record.setId(spuId);
        record.setSaleable(saleable);
        //修改spu
        int count = this.spuMapper.updateByPrimaryKeySelective(record);
        if (1 != count) {
            throw new LyException(ExceptionEnum.DATA_MODIFY_ERROR);
        }
        Sku skuRecord = new Sku();
        skuRecord.setSpuId(spuId);
        //根据spuId查询对应的sku信息
        List<Sku> skus = this.skuMapper.select(skuRecord);

        //循环查询到的sku，修改每个sku的上下架状态
        skus.forEach(sku -> {
            sku.setEnable(saleable);
            sku.setUpdateTime(new Date());
            this.skuMapper.updateByPrimaryKeySelective(sku);
        });

        //TODO sendMessage(MQ);

        // 发送mq消息
        String key = saleable ? ITEM_UP_KEY : ITEM_DOWN_KEY;
        amqpTemplate.convertAndSend(ITEM_EXCHANGE_NAME, key, spuId);
    }

    public SpuDetailDTO querySpuDetailBySpuId(Long spuId) {
        SpuDetail spuDetail = this.spuDetailMapper.selectByPrimaryKey(spuId);

        if (null == spuDetail) {
            throw new LyException(ExceptionEnum.DATA_NOT_FOUND);
        }
        return BeanHelper.copyProperties(spuDetail, SpuDetailDTO.class);
    }

    public List<SkuDTO> querySkuBySpuId(Long spuId) {
        Sku record = new Sku();
        record.setSpuId(spuId);

        List<Sku> skus = this.skuMapper.select(record);

        if (CollectionUtils.isEmpty(skus)) {
            throw new LyException(ExceptionEnum.DATA_NOT_FOUND);
        }

        return BeanHelper.copyWithCollection(skus, SkuDTO.class);
    }

    @Transactional
    public void updateGoods(SpuDTO spuDTO) {
        Spu spu = BeanHelper.copyProperties(spuDTO, Spu.class);

        //修改spu
        int count = this.spuMapper.updateByPrimaryKeySelective(spu);

        if (1 != count) {
            throw new LyException(ExceptionEnum.DATA_MODIFY_ERROR);
        }

        SpuDetail spuDetail = BeanHelper.copyProperties(spuDTO.getSpuDetail(), SpuDetail.class);

        count = this.spuDetailMapper.updateByPrimaryKeySelective(spuDetail);
        if (1 != count) {
            throw new LyException(ExceptionEnum.DATA_MODIFY_ERROR);
        }

        //先要根据spuId删除之前所有的sku
        Sku record = new Sku();
        record.setSpuId(spu.getId());

        //统计数量
        int skuCount = this.skuMapper.selectCount(record);

        count = this.skuMapper.delete(record);

        if (skuCount != count) {
            throw new LyException(ExceptionEnum.DATA_DELETE_ERROR);
        }

        //重建spu和sku的关系
        saveSkus(spuDTO, spu.getId());

    }

    public SpuDTO querySpuById(Long id) {
        Spu spu = this.spuMapper.selectByPrimaryKey(id);

        if (null == spu) {
            throw new LyException(ExceptionEnum.DATA_NOT_FOUND);
        }
        return BeanHelper.copyProperties(spu, SpuDTO.class);
    }

    public List<SkuDTO> querySkuByIds(List<Long> ids) {
        List<Sku> skus = this.skuMapper.selectByIdList(ids);

        if (CollectionUtils.isEmpty(skus)) {
            throw new LyException(ExceptionEnum.DATA_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(skus, SkuDTO.class);
    }

    //减库存会有事务发生，事务提交或者回滚在这里就完成
    @Transactional
    public void minusStock(Map<Long, Integer> cartsMap) {
       cartsMap.entrySet().forEach(entry->{
           Long skuId = entry.getKey();//获取key信息,skuId
           Integer num = entry.getValue(); //获取value信息,当前sku要扣减的数量

           //2,自己写sql语句，通过sql语句扣减库存
           this.skuMapper.minusSkuStock(skuId,num);

       });
    }

    /**
     * 加库存业务
     * @param cartsMap
     */
    public void plusStock(Map<Long, Integer> cartsMap) {
        cartsMap.entrySet().forEach(entry->{
            Long skuId = entry.getKey();//获取key信息,skuId
            Integer num = entry.getValue(); //获取value信息,当前sku要扣减的数量

            //2,自己写sql语句，通过sql语句扣减库存
            this.skuMapper.plusSkuStock(skuId,num);

        });
    }
}
